package com.sakiko.otherai.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Map;

/**
 * projectName: com.sakiko.otherai.controller
 *
 * @author: Yang
 * description: TTS文本转语音实现
 * time: 2025/8/9 12:39
 */
@RestController
public class AudioModelController {

    @Autowired
    private DashScopeSpeechSynthesisModel speechSynthesisModel;

    private static final String TEXT = """
            我乃三转巅峰，何人敢杀我？何人能杀我！
            """;

    private static final String PATH = "_07_springai_other" + File.separator + "src\\main\\resources\\tts";

    @GetMapping("tts") // 豆包 对应前端 static/audio-player.html
    public void tts(@RequestParam(value = "text", defaultValue = TEXT) String text,
                    HttpServletResponse httpResponse) {  // 重命名为 httpResponse以区分
        try {
            // 设置响应头，告诉浏览器这是音频文件
            httpResponse.setContentType("audio/mpeg");
            httpResponse.setHeader("Content-Disposition", "inline; filename=\"output.mp3\"");

            // 生成语音
            DashScopeSpeechSynthesisOptions options =
                    DashScopeSpeechSynthesisOptions.builder()
                            .withSpeed(0.85) // 语速
                            .build();

            // 这里的response是语音合成接口返回的对象
            SpeechSynthesisResponse speechResponse =
                    speechSynthesisModel.call(new SpeechSynthesisPrompt(text, options));

            // 获取音频数据并写入响应流
            ByteBuffer audio = speechResponse.getResult().getOutput().getAudio();
            OutputStream os = httpResponse.getOutputStream();
            os.write(audio.array());
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("tts2")
    public void tts(@RequestParam(value = "text", defaultValue = TEXT) String text) {
        DashScopeSpeechSynthesisOptions options =
                DashScopeSpeechSynthesisOptions.builder()
                        .withSpeed(0.85) // 语速
                        .build();

        SpeechSynthesisResponse response =
                speechSynthesisModel.call(new SpeechSynthesisPrompt(text, options));

        File file = new File(PATH + "/output.mp3");

        // 在创建 File对象后添加
        System.out.println("音频文件将保存到: " + file.getAbsolutePath());

        try (FileOutputStream fos = new FileOutputStream(file)) {
            ByteBuffer audio = response.getResult().getOutput().getAudio();
            fos.write(audio.array());
        } catch (IOException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        }

    }

}
